#include <unistd.h>
#include <stdlib.h>
#include <cstdio>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

void errno_exit(const char *msg)
{
    perror(msg);
    exit(EXIT_FAILURE);
}

#define NUM 1024

int main()
{
    // 检测拷贝的目标文件是否存在，存在则删除
    if (access("test.bak", F_OK) == 0)
    {
        if (unlink("test.bak") == -1)
            errno_exit("unlink");
    }

    int outfd = open("test.bak", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (outfd == -1)
        errno_exit("open");

    int infd = open("tp", O_RDONLY);
    if (infd == -1)
        errno_exit("open");

    char buffer[NUM];
    int n, m;
    while ((n = read(infd, buffer, sizeof(buffer))) > 0)
    {
        m = write(outfd, buffer, n);
        if (m != n)
        {
            errno_exit("write");
        }
    }
    if (n == -1)
        errno_exit("read");

    close(infd);
    close(outfd);

    if (unlink("tp") == -1)
        errno_exit("unlink");
    return 0;
}